package com.cathychen.springactiondemo.web.controllers;

import com.cathychen.springactiondemo.web.model.Ingredient;
import com.cathychen.springactiondemo.web.model.Order;
import com.cathychen.springactiondemo.web.model.Taco;
import com.cathychen.springactiondemo.web.repository.IngredientJpa;
import com.cathychen.springactiondemo.web.repository.TacoJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenjing
 * @date 2020/8/26
 */
@Controller
@RequestMapping("/design")
public class DesignController {
    @Autowired
    private IngredientJpa ingredientJpa;
    @Autowired
    private TacoJpa tocaJpa;

    @GetMapping
    public String showDesignForm(Model model) {
        List<Ingredient> ingredients = new ArrayList<>();
        ingredientJpa.findAll().forEach(ingredients::add);

        Ingredient.Type[] values = Ingredient.Type.values();
        for (Ingredient.Type type : values) {
            model.addAttribute(type.toString(), ingredients.stream()
                    .filter(x -> x.getType().equals(type))
                    .collect(Collectors.toList()));
        }

        model.addAttribute("design", new Taco());

        return "design";
    }

    @PostMapping
    public String processDesign(@Valid Taco design, BindingResult errors, @ModelAttribute Order order) {
        if (errors.hasErrors()) {
            return "design";
        }

        Taco taco = tocaJpa.save(design);
        order.addDesign(taco);

        return "redirect:/orders/current";
    }
}
